package com.codebox.wanandroid.module.todo;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.codebox.common.base.BaseSmartRefreshFragment;
import com.codebox.common.base.Resource;
import com.codebox.common.base.Status;
import com.codebox.common.util.ToastUtils;
import com.codebox.wanandroid.R;
import com.codebox.wanandroid.bean.TodoBean;

import java.util.ArrayList;

/**
 * @author Able
 * @date 2019/1/8
 */
public class TodoListFragment extends BaseSmartRefreshFragment<TodoBean.DatasBean> {
    public static final String STATUS = "STATUS";
    private TodoViewModel mTodoViewModel;
    private int mPageNo = 1;
    private int mStatus;

    public static TodoListFragment newInstance(int status) {
        TodoListFragment fragment = new TodoListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(STATUS, status);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mStatus = getArguments().getInt(STATUS);
        initView();
        onRefresh();
    }

    @Override
    protected boolean needLoadMore() {
        return false;
    }

    private void initView() {
        mTodoViewModel = ViewModelProviders.of(TodoListFragment.this).get(TodoViewModel.class);

        TodoAdapter todoAdapter = new TodoAdapter(R.layout.item_todo_list, R.layout.item_sticky_header, new ArrayList<>());
        setAdapter(todoAdapter);
        todoAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                int id = view.getId();
                if (id == R.id.btn_done) {
                    ToastUtils.showSuccess("done");
                } else if (id == R.id.btn_delete) {
                    ToastUtils.showSuccess("Delete");
                } else if (id == R.id.item_todo_content) {
                    ToastUtils.showInfo(position + "");
                }
            }
        });
    }

    @Override
    protected void getData() {
        mTodoViewModel.getTodo(mPageNo, mStatus).observe(TodoListFragment.this, new Observer<Resource<TodoBean>>() {
            @Override
            public void onChanged(@Nullable Resource<TodoBean> todoBeanResource) {
                Status status = todoBeanResource.status;
                dealWithData(todoBeanResource.data != null ? todoBeanResource.data.getDatas() : null, status);
            }
        });
    }

    @Override
    protected boolean needDividerDecoration() {
        return true;
    }

}
